package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.MemberRespVO;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginUserInterceptor implements HandlerInterceptor {

    //ThreadLocal 同一个线程共享数据
    public static ThreadLocal<MemberRespVO> threadLocal = new ThreadLocal<>();
    
    //目标方法执行前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //后台自动任务调用的接口，进行登录验证时放行
        String uri = request.getRequestURI();
        //路径匹配器
        boolean match = new AntPathMatcher().match("/order/order/status/**", uri);
        boolean aliPay = new AntPathMatcher().match("/payed/notify", uri);
        if (match || aliPay) {
            return true;
        }


        MemberRespVO memberRespVO = new MemberRespVO();
        HttpSession session = request.getSession();
        MemberRespVO member = (MemberRespVO) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            //用户已登录
            threadLocal.set(memberRespVO);
            return true;
        }
        //没登录就去登录
        session.setAttribute("msg","请先进行登录");
        response.sendRedirect("http://auth.gulimall.com/login.html");

        return false;
    }
}
